//
//  RootViewController.m
//  HeartTravel
//
//  Created by dlios on 15-6-29.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "RootViewController.h"
#import "NeighbouringViewController.h"
#import "HTTPTool.h"
#import "SearchDistination.h"
#import "SearchDistinationCell.h"
#import "SearchDistinationReusableView.h"
#import "PlaceViewController.h"



#define WIDTH self.view.frame.size.width

@interface RootViewController ()<UISearchBarDelegate,UICollectionViewDelegate,UICollectionViewDataSource>

@property(nonatomic, retain)UISearchBar *searchBar;
@property(nonatomic, retain)UIButton *searchBtn;
@property(nonatomic, assign)BOOL isSelected;
@property(nonatomic, retain)NSMutableArray *destinationArr;
@property(nonatomic, retain)UICollectionView *collectionView;
@property(nonatomic, retain)SearchDistination *domestiv;
@property(nonatomic, retain)SearchDistination *ovearSears;

@end

@implementation RootViewController

- (void)dealloc{
    
    [_collectionView release];
    [_domestiv release];
    [_ovearSears release];
    [_searchBar release];
    [_searchBtn release];
    [_destinationArr release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //按钮初始化判断
    self.isSelected = YES;
    
    //创建searchbar
    [self createSearchBar];
    
    //创建button
    [self createBtn];
    
    //
    [self createCollectionView];
    
    //创建数据
    [self createData];
    
    //
    
    self.view.backgroundColor = [UIColor cyanColor];


}

/**
 *  创建collectionView视图
 */
- (void)createCollectionView{
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    
    //每一个item大小
    flowLayout.itemSize = CGSizeMake(100, 30);
    //设置最小的列间距
    flowLayout.minimumInteritemSpacing = 10;
    //设置最小的行间距
    flowLayout.minimumLineSpacing = 15;
    //设置四周边框设置
    flowLayout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    //设置头视图
    flowLayout.headerReferenceSize = CGSizeMake(0, 70);
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, -(self.view.frame.size.height-64-49), WIDTH, self.view.frame.size.height-64-49) collectionViewLayout:flowLayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    //打开手势交互
//    self.collectionView.userInteractionEnabled = YES;
    //点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
//    //将手势添加到指定的空间上
    [self.collectionView addGestureRecognizer:tap];
    
    
    //注册
#warning 第一个参数:需要指定注册的类型()
#warning 第二个参数:重用池标志;
    [self.collectionView registerClass:[SearchDistinationCell class] forCellWithReuseIdentifier:@"searchReuse"];
    
    //header视图
    [self.collectionView registerClass:[SearchDistinationReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    
    
    [self.collectionView release];
    [flowLayout release];
}

- (void)tapAction:(UITapGestureRecognizer *)tap{
    [self.searchBar resignFirstResponder];
    [self.collectionView removeGestureRecognizer:tap];

}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    
    if (kind == UICollectionElementKindSectionHeader) {
        SearchDistinationReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView" forIndexPath:indexPath];
        //一定不要再这里面创建视图,而是使用自定义的UIClooectionReusableView,涉及到重用的问题
        
        if (indexPath.section == 0) {
            view.titleLabel.text = self.domestiv.title;
        }else{
            
            view.titleLabel.text = self.ovearSears.title;
        }
        view.titleLabel.font = [UIFont systemFontOfSize:22];
        return view;

    }else{
        //创建一个尾部的View
        return nil;
    }
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{


    SearchDistinationCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"searchReuse" forIndexPath:indexPath];

    if (indexPath.section == 0) {
        
        NSMutableArray *arr = self.domestiv.elements;
        NSDictionary *dic = arr[indexPath.row];
        cell.nameLabel.text = dic[@"name"];
        return  cell;
    }else{
        
        NSMutableArray *arr = self.ovearSears.elements;
        NSDictionary *dic = arr[indexPath.row];
        cell.nameLabel.text = dic[@"name"];
        return cell;
    }
        
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{

    return self.destinationArr.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    SearchDistination *temp = self.destinationArr[section];
    NSArray *arr = temp.elements;
    return arr.count;
    
}

/**
 *  创建searchBar;
 */
- (void)createSearchBar{
    
    //设置搜索textField
    UITextField *searchTextField = [[UITextField alloc]init];
    self.searchBar = [[UISearchBar alloc]init];
    self.searchBar.frame = CGRectMake(0, 0, 0, 0);
    self.searchBar.layer.borderColor = [UIColor grayColor].CGColor;
//    self.searchBar.backgroundColor = [UIColor greenColor];
    self.searchBar.placeholder = @"搜索国家、城市、景区、游记名";
    
    //找到searchBar上的textfield
    searchTextField = [[[self.searchBar.subviews firstObject] subviews] lastObject];
    //设置背景颜色
    searchTextField.backgroundColor = [UIColor colorWithRed:60/255.0 green:156/255.0 blue:170/255.0 alpha:1];;
    //更改占位符字体颜色
    [searchTextField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    searchTextField.layer.cornerRadius = 15;
    //去掉放大镜
    [searchTextField setLeftViewMode:UITextFieldViewModeNever];
//
    self.searchBar.delegate = self;
    self.navigationItem.titleView = self.searchBar;
}
/**
 *  数据解析
 */
- (void)createData{
    
    
    NSString *url = @"http://api.breadtrip.com/destination/v3/";
    [HTTPTool get:url body:nil httpResult:JSON success:^(id result) {
        self.destinationArr = [NSMutableArray array];
        
        NSDictionary *dic = result;
        NSArray *arr = dic[@"search_data"];
        NSDictionary *dicOvearSeas = arr[0];
        NSDictionary *dicDomestic = arr[1];
        self.domestiv = [[SearchDistination alloc]initWithDic:dicDomestic];
        self.ovearSears = [[SearchDistination alloc]initWithDic:dicOvearSeas];
        
        [self.destinationArr addObject:self.domestiv];
        [self.destinationArr addObject:self.ovearSears];
        
        [self.collectionView reloadData];
        [self.domestiv release];
        [self.ovearSears release];
        
        

        
    } failure:^(NSError *error) {
        
        NSLog(@"数据错误");
        
    }];
}


/**
 *  创建附近Button
 */
- (void)createBtn{
    
    
    self.searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    if (self.isSelected) {
        
        [self.searchBtn setTitle:@"附近" forState:UIControlStateNormal];
    }else{
        [self.searchBtn setTitle:@"取消" forState:UIControlStateNormal];
    }
    self.searchBtn.frame = CGRectMake(0, 0, 50, 50);
    [self.searchBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.searchBtn];
    [self.searchBtn addTarget:self action:@selector(clickBtn) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)clickBtn{
    if (self.isSelected) {
        NeighbouringViewController *neighbouringVC = [[NeighbouringViewController alloc]init];
        
        //push后隐藏tabbar
        neighbouringVC.hidesBottomBarWhenPushed = YES;
        
        [self.navigationController pushViewController:neighbouringVC animated:YES];
        [neighbouringVC release];
    }else{
        self.isSelected = YES;
        [UICollectionView animateWithDuration:0.5 animations:^{
            
            self.collectionView.frame = CGRectMake(0, - (self.view.frame.size.height-64-49), WIDTH, self.view.frame.size.height-64-49);
        }];
        [self.searchBar resignFirstResponder];
        [self createBtn];
    }
}



- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    self.isSelected = NO;
    [UICollectionView animateWithDuration:0.5 animations:^{
        
        self.collectionView.frame = CGRectMake(0, 0, WIDTH, self.view.frame.size.height);
    }];
//    self.collectionView.userInteractionEnabled = YES;
//    [self.collectionView removeGestureRecognizer:tan];
    [self createBtn];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
 
    PlaceViewController *place = [[PlaceViewController alloc] init];

    
    SearchDistination *modelTemp = self.destinationArr[indexPath.section];
    NSArray *arrTemp = modelTemp.elements;
    NSDictionary *dicTemp = arrTemp[indexPath.row];
    NSLog(@"%@",dicTemp[@"id"]);
    place.bId = dicTemp[@"id"];
    place.type = dicTemp[@"type"];
//    place.type = dicTemp[
    
    [self.navigationController pushViewController:place animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
